﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Infrastructure.Middlewares;
using Casamiel.Application;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Response;
using MediatR;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class StaffLoginCommandHandler : IRequestHandler<StaffLoginCommand, BaseResult<TokenEntity>>
    {
        private readonly IMemberService _memberService;
        private readonly ITokenProvider _tokenProvider;
        private readonly IUserLogService _userLog;
        private readonly IStaffService _staffService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tokenProvider"></param>
        /// <param name="memberService"></param>
        ///<param name="staffService"></param>
        /// <param name="userLogService"></param>
        public StaffLoginCommandHandler(ITokenProvider tokenProvider, IMemberService memberService, IStaffService staffService,IUserLogService userLogService)
        {
            _tokenProvider = tokenProvider;
            _memberService = memberService;
            _staffService = staffService;
            _userLog = userLogService;
        }

       /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BaseResult<TokenEntity>> Handle(StaffLoginCommand request, CancellationToken cancellationToken)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }
            var hlentity = await _staffService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
            if (hlentity == null)
            {
                return new BaseResult<TokenEntity>(null, 9999, "用户不存在！");
            }
            var password = Common.Utilities.SecurityUtil.EncryptText(request.Password, hlentity.PasswordSalt);
            if (password != hlentity.Password)
            {
                return new BaseResult<TokenEntity>(null, 9999, "密码不对！");
            }

            var token = _tokenProvider.GenerateToken(request.Mobile);
           // token.expires_in = 1800;
            var m = await _memberService.FindAsync<ICasaMielSession>(request.Mobile, request.LogType).ConfigureAwait(false);
            if (m != null) {
                m.Access_Token = token.access_token;
                m.UpdateTime = DateTime.Now;
                m.Login_Count++;
                m.Expires_In = token.expires_in;
                m.Resgistration_Id = request.RegistrationId;
                await _memberService.UpdateAsync<ICasaMielSession>(m).ConfigureAwait(false);
            } else {
                m = new MemberAccessToken {
                    Access_Token = token.access_token,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Login_Count = 1,
                    Login_Type = request.LogType,
                    Mobile = request.Mobile,
                    Expires_In = token.expires_in,
                    Resgistration_Id = request.RegistrationId
                };
                await _memberService.AddAsync<ICasaMielSession>(m).ConfigureAwait(false);
            }
            var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"用户登陆", OPTime = DateTime.Now, UserName = request.Mobile, UserIP = request.UserIP };
            await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
            return new BaseResult<TokenEntity>(token, 0, "");
        }
    }

}

